package Network.homework;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket socket=null;
    public TcpEchoServer(int port) throws IOException {
        socket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService pool = Executors.newCachedThreadPool();
        while(true){//每来一个连接,就接听
            //1.建立连接
            Socket clientSocket=socket.accept();
//            //2.连接
//            processConnection(clientSocket);
            //多线程
//            new Thread(()->{
//                processConnection(clientSocket);
//            }).start();
            //通过创建线程池,使用多线程处理多个客户的请求
            pool.submit(new Runnable(){
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }
    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s,%d] 客户端上线\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream=clientSocket.getInputStream();
            OutputStream outputStream=clientSocket.getOutputStream()){
            while(true){
                //1.获取请求 通过Scanner读取字节流
                Scanner scan=new Scanner(inputStream);
                if(!scan.hasNext()){//注意,这里是以空白字符结尾的,
                                    // 当请求中有空白字符内容时,可进行多次请求
                    System.out.printf("[%s,%d] 客户端下线\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //获取请求
                String request=scan.next();
                //2.解析响应
                String response=process(request);
                //3.返回响应 给outputStream封装在PrintWriter中,方便使用 可以获取到 \n
                PrintWriter printWriter=new PrintWriter(outputStream);
                //通过 printWriter.println返回响应
                printWriter.println(response);
                printWriter.flush();//要刷新缓冲区
                System.out.printf("[%s,%d] req:%s, resp:%s\n",clientSocket.getInetAddress(),clientSocket.getPort(),
                                                        request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
